package cn.itrip.auth.controller;

import cn.itrip.auth.service.SmsService;
import cn.itrip.auth.service.UserService;
import cn.itrip.beans.domain.ItripUser;
import cn.itrip.beans.dtos.Dto;
import cn.itrip.common.DtoUtils;
import cn.itrip.common.ErrorUtil;
import cn.itrip.common.MD5;
import cn.itrip.common.RedisAPI;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/api")
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private RedisAPI redisAPI;
    /**
     * 使用邮箱注册
     * @param users
     * @return
     */
    @RequestMapping(value="/doregister",method=RequestMethod.POST,produces = "application/json")
    public @ResponseBody
    Dto doRegister(
            @ApiParam(name="userVO",value="用户实体",required=true)
            @RequestBody ItripUser users) {
        if(!validEmail(users.getUserCode()))
            return  DtoUtils.returnFail("请使用正确的邮箱地址注册",ErrorUtil.AUTH_ILLEGAL_USERCODE);

        try {
            ItripUser user=new ItripUser();
            user.setUserCode(users.getUserCode());
            user.setUserPassword(users.getUserPassword());
            user.setUserType(0);
            user.setUserName(users.getUserName());
            if (null == userService.findByUsername(user.getUserCode())) {
                user.setUserPassword(MD5.md5(user.getUserPassword()));
                userService.itriptxCreateUser(user);
                return DtoUtils.returnSuccess("注册成功");
            }else
            {
                return DtoUtils.returnFail("用户已存在，注册失败", ErrorUtil.AUTH_USER_ALREADY_EXISTS);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtils.returnFail(e.getMessage(), ErrorUtil.AUTH_UNKNOWN);
        }

    }

    /**
     * 激活邮箱
     * @param user
     * @param code
     * @return
     */
    @RequestMapping(value="/activate",method=RequestMethod.PUT,produces= "application/json")
    public @ResponseBody Dto activate(@RequestParam String user, @RequestParam String code){
        return action(user, code);
    }
    /**
     * 使用手机注册
     * @param users
     * @return
     */
    @PostMapping("/registerbyphone")
    @RequestMapping(value="/registerbyphone",method=RequestMethod.POST,produces = "application/json")
    public @ResponseBody Dto registerByPhone(
            @ApiParam(name="users",value="用户实体",required=true)
            @RequestBody ItripUser users){
        try {
            if(!validPhone(users.getUserCode()))
                return  DtoUtils.returnFail("请使用正确的手机号注册", ErrorUtil.AUTH_ILLEGAL_USERCODE);

            ItripUser user=new ItripUser();
            user.setUserCode(users.getUserCode());
            user.setUserPassword(users.getUserPassword());
            user.setUserType(0);
            user.setUserName(users.getUserName());
            //重名判断
            if (null == userService.findByUsername(user.getUserCode())) {
                user.setUserPassword(MD5.md5(user.getUserPassword()));
                userService.itriptxCreateUserByPhone(user);
                return DtoUtils.returnSuccess();
            }else {
                return DtoUtils.returnFail("手机号已存在，注册失败", ErrorUtil.AUTH_USER_ALREADY_EXISTS);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtils.returnFail(e.getMessage(),ErrorUtil.AUTH_UNKNOWN);
        }
    }

    //验证用户名
    /**
     * 检查用户是否已注册
     * @param name
     * @return
     */
    @RequestMapping(value="/ckusr",method=RequestMethod.GET,produces= "application/json")
    public @ResponseBody Dto checkUser(
            @ApiParam(name="name",value="被检查的用户名",defaultValue="test@bdqn.cn")
            @RequestParam String name) {
        try {
		/*	if(!validEmail(name))
				return  DtoUtil.returnFail("请使用正确的邮箱地址注册",ErrorUtil.AUTH_ILLEGAL_USERCODE);*/
            if (null == userService.findByUsername(name))
            {
                return DtoUtils.returnSuccess("用户名可用");
            }
            else
            {
                return DtoUtils.returnFail("用户已存在，注册失败", ErrorUtil.AUTH_USER_ALREADY_EXISTS);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtils.returnFail(e.getMessage(), ErrorUtil.AUTH_UNKNOWN);
        }
    }
    //激活手机
    @RequestMapping(value="/validatephone",method=RequestMethod.PUT,produces= "application/json")
    public @ResponseBody Dto validatePhone(
            @RequestParam String user,
            @RequestParam String code){
        return action(user, code);
    }
//手机邮箱激活方法
    private Dto action(@RequestParam String user, @RequestParam String code) {
        String codes = redisAPI.get(user);
        System.out.println(codes);
        if(userService.selectByUserCode(user) != null){
            if (code.equals(codes)) {
                int num = userService.updateItripUser(user);
                if (num > 0) {
                    return DtoUtils.returnSuccess("激活成功");
                } else {
                    return DtoUtils.returnFail("激活失败", ErrorUtil.AUTH_ACTIVATE_FAILED);
                }
            } else {
                return DtoUtils.returnFail("验证码错误", ErrorUtil.AUTH_ACTIVATE_FAILED);
            }
        }else{
            return DtoUtils.returnFail("该用户不存在",ErrorUtil.AUTH_ACTIVATE_FAILED);
        }
    }
    /**
     * 验证是否合法的手机号
     * @param phone
     * @return
     */
    private boolean validPhone(String phone) {
        String regex="^1[3578]{1}\\d{9}$";
        return Pattern.compile(regex).matcher(phone).find();
    }
    /**			 *
     * 合法E-mail地址：
     * 1. 必须包含一个并且只有一个符号“@”
     * 2. 第一个字符不得是“@”或者“.”
     * 3. 不允许出现“@.”或者.@
     * 4. 结尾不得是字符“@”或者“.”
     * 5. 允许“@”前的字符中出现“＋”
     * 6. 不允许“＋”在最前面，或者“＋@”
     */
    private boolean validEmail(String email){

        String regex="^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$"  ;
        return Pattern.compile(regex).matcher(email).find();
    }
}
